<template>
  <div>
    <el-row style="height: 65px;">
      <el-col :span="6">
        <el-button type="primary"  :icon="CirclePlus" @click="dialogAddForm = true">
          添加门店
        </el-button>
        <el-button type="success"  :icon="Upload" style="margin-left:25px;" @click="exportExcel">
          导出全部数据
        </el-button>
      </el-col>
      <el-col :span="3">
        <el-upload
          action="http://localhost:3030/store/import/excel/"
          :on-success="handleImportSuccess"
          :on-error="handleImportError"
          :headers="myHeaders"  
        >
        <el-button type="info"  :icon="Download">导入数据</el-button>
      </el-upload>
      </el-col>
    </el-row>
    <el-row style="margin-bottom: 10px;">
      <el-col :span="12">
        <el-select
          v-model="select_types"
          multiple
          :multiple-limit="3"
          tag-type="success"
          style="width:330px;"
          filterable
          allow-create
          default-first-option
          :reserve-keyword="false"
          placeholder="选择门店的类型"
        >
          <el-option v-for="value in industry_type" :key="value" :value="value"/>
        </el-select>
        <el-button  type="success" :icon="Search" style="margin-left: 10px;" @click="getStoreByType">搜索</el-button>
        <el-button  type="primary" :icon="Help" style="margin-left: 10px;" @click="getStore">全部数据</el-button>
      </el-col>
      <el-col :span="8" :offset="4">
        <el-input style="width: 38%;margin-right: 2%;" :suffix-icon="Opportunity" v-model="searchCondition.storeName" placeholder="请输入名称"></el-input>
        <el-input style="width: 37%;" :suffix-icon="Stamp" v-model="searchCondition.storeBoss" placeholder="请输入负责人"></el-input>
        <el-button  type="info" :icon="Search" style="margin-left: 3%;" @click="getStoreByLike">搜索</el-button>
      </el-col>
    </el-row>
    <el-dialog draggable v-model="dialogAddForm" title="添加门店" width="35%" :align-center="true">
      <el-form :model="form" label-width="120px">
        <el-form-item label="门店名称">
          <el-input v-model="form.name"/>
        </el-form-item>
        <el-form-item  label="商标">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:3030/store/upload/logo/"
            :headers="myHeaders"
            :show-file-list="false"
            :on-success="addLogoSuccess"
            :before-upload="beforeLogoUpload"
          >
            <img :src="form.logo" class="avatar" />
          </el-upload>
        </el-form-item>
        <el-form-item label="负责人">
          <el-input v-model="form.bossName"/>
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="form.phone"/>
        </el-form-item>
        <el-form-item label="店长">
          <el-input v-model="form.manager"/>
        </el-form-item>
        <el-form-item label="门店地址">
          <el-input v-model="form.address"/>
        </el-form-item>
        <el-form-item label="门店面积(㎡)">
          <el-input v-model="form.area" :min="20"/>
        </el-form-item>
        <el-form-item label="营业时间">
            <el-time-select
              style="width: 40%; margin-right: 10%;"
              v-model="startTime1"
              :max-time="endTime1"
              class="mr-4"
              placeholder="开始营业"
              start="04:00"
              step="00:15"
              end="12:00"
            />
            <el-time-select
              style="width: 40%;"
              v-model="endTime1"
              :min-time="startTime1"
              placeholder="结束营业"
              start="16:00"
              step="00:15"
              end="23:30"
            />
        </el-form-item>
        <el-form-item label="所属行业">
          <el-select v-model="form.type" placeholder="所属行业">
            <el-option
              v-for="value in industry_type" :key="value" :value="value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogAddForm = false">关闭</el-button>
          <el-button type="primary" @click="addStore">
            添加
          </el-button>
        </span>
      </template>
    </el-dialog>
    <el-table border stripe :data="stores" height="430px" style="width: 100%;margin-top: 10px;" 
      @selection-change="handleSelect"
      :header-cell-style="{'background':'#b1b3b8','text-align':'center','color':'white'}" :cell-style="{'text-align':'center'}">
      <el-table-column type="selection" width="50" /> 
      <el-table-column prop="name" label="门店名称" width="120"/>
      <el-table-column label="商标" width="100">
        <template #default="scope">
          <el-image :src="scope.row.logo" style="width: 42px; height: 42px;border-radius: 25%;" />
        </template>
      </el-table-column>
      <el-table-column prop="bossName" label="负责人" width="80"/>
      <el-table-column prop="manager" label="店长" width="80"/>
      <el-table-column prop="business" label="营业时间" width="110" />
      <el-table-column prop="phone" label="联系方式" width="120" />
      <el-table-column prop="area" label="面积" width="60"/>
      <el-table-column prop="type" label="类型" width="100"/>
      <el-table-column prop="address" label="地址" width="250"/>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="warning"  :icon="Edit" @click="handleEdit(scope.row)" circle size="large" ></el-button>
          <el-dialog :append-to-body="true" :align-center="true" draggable v-model="scope.row.dialog" title="编辑信息" width="35%">
            <el-form :model="editData" label-width="120px">
              <el-form-item  label="门店名称">
                <el-input v-model="editData.name" />
              </el-form-item>
              <el-form-item  label="商标">
                <el-upload
                  class="avatar-uploader"
                  action="http://localhost:3030/store/upload/logo/"
                  :headers="myHeaders"
                  :show-file-list="false"
                  :on-success="handleLogoSuccess"
                  :before-upload="beforeLogoUpload"
                >
                  <img :src="editData.logo" class="avatar" />
                </el-upload>
              </el-form-item>
              <el-form-item label="负责人">
                <el-input v-model="editData.bossName"  />
              </el-form-item>
              <el-form-item label="联系电话">
                <el-input v-model="editData.phone" />
              </el-form-item>
              <el-form-item label="店长">
                <el-input v-model="editData.manager"  />
              </el-form-item>
              <el-form-item label="门店地址">
                <el-input v-model="editData.address"  />
              </el-form-item>
              <el-form-item label="门店面积(㎡)">
                <el-input v-model="editData.area"  :min="20"/>
              </el-form-item>
              <el-form-item label="营业时间">
                  <el-time-select
                    style="width: 40%; margin-right: 10%;"
                    :max-time="endTime2"
                    class="mr-4"
                    placeholder="开始营业"
                    v-model="startTime2"
                    start="04:00"
                    step="00:15"
                    end="12:00"
                  />
                  <el-time-select
                    style="width: 40%;"
                    :min-time="startTime2"
                    v-model="endTime2"
                    placeholder="结束营业"
                    start="16:00"
                    step="00:15"
                    end="23:30"
                  />
              </el-form-item>
              <el-form-item label="所属行业">
                <el-select v-model="editData.type" placeholder="所属行业">
                  <el-option v-for="value in industry_type" :key="value" :value="value"/>
                </el-select>
              </el-form-item>
            </el-form>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="scope.row.dialog = false">关闭</el-button>
                <el-button type="primary" @click="updateStore($store.state.user.role,scope.row)">
                  修改
                </el-button>
              </span>
            </template>
          </el-dialog>
          <el-popconfirm
              width="220"
              confirm-button-text="确认"
              cancel-button-text="我再想想"
              cancel-button-type="info"
              :icon="InfoFilled"
              icon-color="red"
              title="你确定删除吗?"
              @confirm="handleDelete(scope.row)"
            >
              <template #reference>
                <el-button type="danger" style="margin-left: 20px;" :icon="Delete" size="large" circle ></el-button>
              </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-row style="margin-top: 20px;">
      <el-col :span="10">
        <el-tag type="success" style="height: 32px; vertical-align: middle;font-size: 17px;">
          已选择 <span style="color: #79bbff;margin-right: 5px;">{{selected_count}}</span>条记录
        </el-tag>
        <el-button type="danger" :icon="DeleteFilled" @click="bulk_deletion" plain style="margin-left: 15px;">批量删除</el-button>
        <el-button type="success" :icon="Promotion" @click="batchExport" plain style="margin-left: 15px;">批量导出</el-button>
      </el-col>
      <el-col :span="2"></el-col>
      <el-col :span="12">
        <div class="demo-pagination-block" style="float: right;">
          <el-pagination
            v-model:current-page="currentPage"
            :page-size="6"
            :total="total"
            :background="true"
            layout="prev, pager, next"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-col>
    </el-row>
    </div>
</template>
<script>
    import { ref,reactive } from 'vue'
    import {useStore} from 'vuex'
    import request from '@/utils/request'
    import {CirclePlus,Edit,Delete,InfoFilled,Search,Stamp,Opportunity,Help,
            DeleteFilled,Upload,Download,Promotion} from '@element-plus/icons-vue'
    import { ElMessage} from 'element-plus'
    export default{
        name:'StoreInfo',
        setup() {
            let dialogAddForm = ref(false)
            const store = useStore()
            const icon  = {CirclePlus,Opportunity,Search,Help, Edit,Delete,Stamp, InfoFilled,DeleteFilled,Upload,Download,Promotion}
            let industry_type = ref(['餐饮','服装','休闲娱乐','运动竞技','电子产品','地摊经济','其他'])
            let select_types = ref([])//选择查询的门店类型
            let startTime1 = ref('')
            let endTime1 = ref('')
            let startTime2 = ref('')
            let endTime2 = ref('')
            let selected_count = ref(0)
            let currentPage = ref(1)
            let total = ref(6)
            let deleteSelect = ref([]) //批量删除的用户id集合
            let searchCondition = reactive({
              storeName:'',
              storeBoss:'',
            })
            let form = reactive({ //添加时form表单数据
                name: '',bossName:'',phone:'',manager:'',
                type:'',address:'',business: '',area:30,
                logo:'https://s1.ax1x.com/2023/02/09/pSWOnUI.png',
            })
            let editData = ref({}) 
            let stores = ref([])
            //上传商标
            const addLogoSuccess = (resp) => {
              form.logo = "http://localhost:3030" + resp.logoUrl
            }
            const handleLogoSuccess = (resp) => {
              editData.value.logo = "http://localhost:3030" + resp.logoUrl
            }
            const beforeLogoUpload = () => {
            }
            //模糊查询
            const getStoreByLike = () => {
              if(searchCondition.storeName !== '' || searchCondition.storeBoss !== ''){
                request({
                  url:'/store/get/Like/',
                  method:'get',
                  params:{
                    ...searchCondition,
                    username:store.state.user.username,
                    role:store.state.user.role,
                  },
                  headers:{
                    Authorization:"Bearer "+store.state.user.token,
                  }
                }).then((resp) => {
                  for (const store of resp) {
                    store.dialog = false
                  }
                  stores.value = resp;
                  total.value = 6;
                }).catch(() => {
                })
              } 
            }
            //搜索该类型的数据
            const getStoreByType = () => {
              request({
                url:'/store/get/byType/',
                method:'post',
                data:{
                  types:JSON.stringify(select_types.value),
                  username:store.state.user.username,
                  role:store.state.user.role
                }, 
                headers:{
                  Authorization:"Bearer "+store.state.user.token,
                }
              }).then((resp)=>{
                for (const store of resp) {
                  store.dialog = false
                }
                stores.value = resp;
                total.value = 6;
              }).catch((err)=>{
                console.log(err)
              })
            }
            //导出Excel
            const exportExcel = function(){
              request({
                url:'/store/exportAll/',
                method:'get',
                headers:{
                  Authorization:"Bearer "+store.state.user.token,
                },
                responseType:'blob',//需要设置响应类型为blob,响应的数据为二进制数据，否则文件会被损坏
              }).then((resp) => {
                //Blob为二进制数据的容器
                let blob = new Blob([resp], {type: 'application/vnd.ms-excel'});
                let url = URL.createObjectURL(blob);
                const link = document.createElement('a'); //创建a标签
                link.href = url;
                link.download = '门店信息.xlsx'; //重命名文件
                link.click();
                URL.revokeObjectURL(url);
              })
            }
            //导入
            const handleImportSuccess = () => {
              ElMessage.success('导入成功')
              getStore(store.state.user.username,store.state.user.role,currentPage.value)
            }
            const handleImportError = () => {
              ElMessage.error('导入失败')
              getStore()
            }
            const myHeaders = ref({
              Authorization:"Bearer "+store.state.user.token
            })
            const handleSelect = function(selected){
              selected_count.value = selected.length;
              for (const store of selected) {
                deleteSelect.value.push(store.id)
              }
            }
            //批量删除
            const bulk_deletion = function(){
              if(selected_count.value !== 0){
                request({
                  url:'/store/deleteSelect/',
                  method:'post',
                  data:JSON.stringify({
                    role:store.state.user.role,
                    select:JSON.stringify(deleteSelect.value)
                  }),
                  headers:{
                    Authorization:"Bearer "+store.state.user.token,
                  },
                }).then((resp)=>{
                  if(resp.message === 'success'){
                      getStore()
                      ElMessage({message: '删除成功!',type: 'success'})
                      deleteSelect.value = []
                    }else if(resp.message === 'error'){
                      ElMessage({message: '没有权限!',grouping: true,type: 'error'})
                    }
                }).catch(() => {
                });
              }else{
                ElMessage({message: '请勾选删除的选项!',grouping: true,type: 'warning'})
              }
            }
            //批量导出
            const batchExport = () =>  {
              if(selected_count.value !== 0){
                request({
                  url:'/store/export/',
                  method:'post',
                  data:JSON.stringify(deleteSelect.value),
                  headers:{
                    Authorization:"Bearer "+store.state.user.token,
                  },
                  responseType:'blob',
                }).then((resp) => {
                    let blob = new Blob([resp], {type: 'application/vnd.ms-excel'});
                    let url = URL.createObjectURL(blob);
                    const link = document.createElement('a'); //创建a标签
                    link.href = url;
                    link.download = '部门门店信息.xlsx'; //重命名文件
                    link.click();
                    URL.revokeObjectURL(url);
                    deleteSelect.value = []
                }).catch(() => {
                  ElMessage({message: '导出失败!',type: 'error'})
                })
              }else{
                ElMessage({message: '请勾选导出的选项!',grouping: true,type: 'warning'})
              }
            }
            //获取门店
            let getStore = function(){
              request({
                    url:'/store/get/',
                    method:'get',
                    params:{
                      role:store.state.user.role,
                      username:store.state.user.username,
                      page:currentPage.value
                    },
                    headers:{
                      Authorization:"Bearer "+store.state.user.token,
                    }
                }).then((resp) => {
                    for (const iterator of resp.stores) {
                      iterator.dialog = false
                    }
                    stores.value = resp.stores;
                    total.value = resp.total;
                }).catch(() => {
                });
            }
            getStore()
            //添加门店
            let addStore = function(){
                form.business = startTime1.value + "-" + endTime1.value
                dialogAddForm.value = false;
                request({
                    url:'/store/add/',
                    method:'post',
                    data:JSON.stringify({...form}),
                    headers:{
                      Authorization:"Bearer "+store.state.user.token,
                    }
                }).then(() => {
                    getStore()
                    ElMessage({message: '添加成功!',type: 'success'})
                }).catch(() => {
                    ElMessage({message: '添加失败!',grouping: true,type: 'error'})
                });
            }
            // 编辑门店信息
            let updateStore = function(role,storeData){
              editData.value.business = startTime2.value+"-"+endTime2.value
              request({
                url:'/store/update/',
                method:'post',
                data:{...(editData.value),role},
                headers:{
                  'Content-Type':'application/x-www-form-urlencoded',
                  Authorization:"Bearer "+store.state.user.token,
                }
              }).then((resp) => {
                  if(resp.message === 'success'){
                    getStore()
                    storeData.dialog = false
                    ElMessage({message: '编辑成功!',type: 'success',})
                  }else if(resp.message === 'error'){
                    getStore()
                    storeData.dialog = false
                    ElMessage({message: '没有权限!',grouping: true,type: 'error'})
                  }
                }).catch(() => {
                });
            }
            // 删除门店
            let deleteStore = function(id,role){
              request({
                url:'/store/delete/',
                method:'post',
                data:{id,role},
                headers:{
                  Authorization:"Bearer "+store.state.user.token,
                }
              }).then((resp)=>{
                if(resp.message === 'success'){
                    getStore()
                    ElMessage({message: '删除成功!',type: 'success'})
                  }else if(resp.message === 'error'){
                    ElMessage({message: '没有权限!',grouping: true,type: 'error'})
                  }
              }).catch(()=>{})
            }
            const handleEdit = (row) => {
              for (const store of stores.value) {
                if(store.id === row.id){
                  editData.value = store
                  startTime2.value = store.business.substring(0,5)
                  endTime2.value = store.business.substring(6,11)
                  store.dialog = true
                }
              }
            }
            const handleDelete  = (row) => {
              deleteStore(row.id,store.state.user.role)
            }
            const handleCurrentChange = (value) =>{
              currentPage.value = value
              getStore()
            }
            return {
              getStoreByType,
              handleImportSuccess,
              handleImportError,
              handleLogoSuccess,
              addLogoSuccess,
              beforeLogoUpload,
              searchCondition,
              getStoreByLike,
              myHeaders,
              handleSelect,
              bulk_deletion,
              batchExport,
              exportExcel,
              dialogAddForm,
              currentPage,
              addStore,
              updateStore,
              startTime1,
              endTime1,
              startTime2,
              endTime2,
              selected_count,
              stores,
              total,
              industry_type,
              select_types,
              form,
              editData,
              ...icon,
              handleDelete,
              handleEdit,
              handleCurrentChange,
              getStore
            }
        },
    }
</script>
<style scoped> 
.el-input {
  width: 300px;
}
.span{
  display: inline-block;
  width: 20px;
  height: 18px;
  text-align: center;
}
.avatar-uploader .avatar {
  width: 50px;
  height: 50px;
  display: block;
}
</style>
<style>
  .avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 50px;
  height: 50px;
  text-align: center;
}
</style>